//
//  RequestNetwork.m
//  work1
//
//  Created by zhoudong on 2018/5/15.
//  Copyright © 2018年 session. All rights reserved.
//

//
//  Work.m
//  WatsonUser
//
//  Created by zhoudong on 2018/5/15.
//  Copyright © 2018年 zhoudong. All rights reserved.
//

#import "RequestNetwork.h"


@implementation RequestNetwork{
    
    RequestCallBackBlock   mBlock;
}


- (instancetype)init {
    return [self initWithBaseURL:nil];
}

- (instancetype)initWithBaseURL:(NSURL *)url {
    self = [super init];
    if (!self) {
        return nil;
    }
    if(_receiveData == nil)
        _receiveData = [[NSMutableData alloc] init];
 
    
    return self;
}

-(NSURLSessionDataTask*)postReq:(NSString*)url sysSession:(NSString*)session0 reqData:(NSDictionary*)p back:(RequestCallBackBlock)block{
    
  
    
    if(url == nil || p==nil) return nil;
    mBlock = block;
    
    //确定请求路径
    NSURL *url0 = [NSURL URLWithString:url];
    //创建可变请求对象
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url0];
    [request setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
   
    
    //seeion 放到head里面
    [request  setValue:session0 forHTTPHeaderField:@"session_ID"];
    
    
    //设置请求方法
    request.HTTPMethod = @"POST";

    request.timeoutInterval = 30.0;
    
    
   // 0101010010101001001001
    //设置请求体  
    request.HTTPBody = [[self convertToJSONData:p] dataUsingEncoding:NSUTF8StringEncoding];
  
    
    //创建会话对象，设置代理
    NSURLSession *session = [NSURLSession sessionWithConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]
                                                          delegate:self delegateQueue:nil];
    //创建请求 Task
    NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request];
    //发送请求
    [dataTask resume];
    
    return dataTask;
}


#pragma mark -- NSURLSessionDataDelegate// 1.接收到服务器的响应
- (void)URLSession:(NSURLSession *)session dataTask:(NSURLSessionDataTask *)dataTask didReceiveResponse:(NSURLResponse *)response completionHandler:(void (^)(NSURLSessionResponseDisposition))completionHandler {
    //【注意：此处需要允许处理服务器的响应，才会继续加载服务器的数据。 若在接收响应时需要对返回的参数进行处理(如获取响应头信息等),那么这些处理应该放在这个允许操作的前面。】
    completionHandler(NSURLSessionResponseAllow);
    
  
}

// 2.接收到服务器的数据（此方法在接收数据过程会多次调用）
- (void)URLSession:(NSURLSession *)session dataTask:(NSURLSessionDataTask *)dataTask didReceiveData:(NSData *)data {
   // body
    [self.receiveData appendData:data];
   
    
}
// 3.3.任务完成时调用（如果成功，error == nil）
- (void)URLSession:(NSURLSession *)session task:(NSURLSessionTask *)task didCompleteWithError:(NSError *)error {
    if(error == nil){
       
      NSString* data =  [[NSString alloc] initWithData: self.receiveData encoding:NSUTF8StringEncoding];
        id dic = [self dictionaryWithJsonString:data];
        if(mBlock!= nil){
            
            mBlock(dic ,@"网络请求成功",200);
        }else{
            NSInteger errCode = error.code;
            mBlock(nil,[self getErroMsg:errCode],errCode);
        }
        
    }
    
}



-(NSString*)getErroMsg:(NSInteger)code{
    
    switch (code) {
        case 404:
            return @"网络连接失败";
            break;
            
        case 500:
            return @"拒绝请求";
            break;
            
        case 700:{
            
               return @"session过期";//1小时
            //同步网络请求 去获取session
        }
         
            break;
            
        case 800:
            return @"服务器端bug 后台gg正在维护中";
            break;
            
        default:
            break;
    }
    
    return @"未定义错误";
}


-(NSDictionary *)dictionaryWithJsonString:(NSString *)jsonString
{
    if (jsonString == nil) {
        return nil;
    }
    
    NSData *jsonData = [jsonString dataUsingEncoding:NSUTF8StringEncoding];
    NSError *err;
    NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:jsonData
                                                        options:NSJSONReadingMutableContainers
                                                          error:&err];
    if(err)
    {
        NSLog(@"json解析失败：%@",err);
        return nil;
    }
    return dic;
}
- (NSString*)convertToJSONData:(id)infoDict
{
    NSError *error;
    NSData *jsonData = [NSJSONSerialization dataWithJSONObject:infoDict
                                                       options:NSJSONWritingPrettyPrinted // Pass 0 if you don't care about the readability of the generated string
                                                         error:&error];
    
    NSString *jsonString = @"";
    
    if (! jsonData)
    {
        NSLog(@"Got an error: %@", error);
    }else
    {
        jsonString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
    }
    
    jsonString = [jsonString stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];  //去除掉首尾的空白字符和换行字符
    
    [jsonString stringByReplacingOccurrencesOfString:@"\n" withString:@""];
    
    return jsonString;
}
@end
